package com.study.spmongodb.wwj.juc.utils;

import java.util.Random;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;

/**
 * @author MI
 * @version 1.0
 * @date 2020/12/13 21:43
 */
public class PhaserExample4 {
    private final static Random random = new Random(System.currentTimeMillis());

    public static void main(String[] args) {
        final Phaser phaser = new Phaser(1);
       /* phaser.arriveAndAwaitAdvance();
        System.out.println(phaser.getPhase());

        phaser.arriveAndAwaitAdvance();
        System.out.println(phaser.getPhase());

        phaser.arriveAndAwaitAdvance();
        System.out.println(phaser.getPhase());

        phaser.arriveAndAwaitAdvance();
        System.out.println(phaser.getPhase());*/


        final Phaser phaser1 = new Phaser(2) {
            @Override
            protected boolean onAdvance(int phase, int registeredParties) {
                return false;
            }
        };

        new OnAdvanceTask("Alex", phaser1).start();
        new OnAdvanceTask("Jack", phaser1).start();
    }

    static class OnAdvanceTask extends Thread {
        private final Phaser phaser;

        public OnAdvanceTask(String name, Phaser phaser) {
            super(name);
            this.phaser = phaser;
        }

        @Override
        public void run() {
            System.out.println(getName() + " i am start " + phaser.getPhase());
            phaser.arriveAndAwaitAdvance();
            System.out.println(getName() + " i am end！");

            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(getName() + " i am start " + phaser.getPhase());
            phaser.arriveAndAwaitAdvance();
            System.out.println(getName() + " i am end！");
        }
    }
}
